import { Ref, useState, useRef, useEffect } from 'react';
import { Button, Table, message, Form, Row, Col, Input } from 'antd';

import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { getKeyRouter, onCloseModalCommon } from '@/utils';
import { commonPageSizeOptions, showTotalInfo } from '@/common/constVariable';

import '../common/styles.less';
import { getSourceListService } from '../services';
import { setTableRowClassName } from '../common/Format';
import { getProjectTableColumns } from '../mconfig';

/**
 * @SourceListModal 选择项目
 * @param onClose 关闭弹窗组件
 * @param onSave 保存事件
 * @returns
 */
const SourceListModal: React.FC<Record<string, any>> = ({ onClose, onSave, curRes }) => {
  const [searchForm] = Form.useForm(); /**查询条件表单实例*/
  const reloadLayoutRef: Ref<IOneModalRef> = useRef(null); /**弹窗Ref*/
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]); /**表格选中行的key*/
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]); /**物料表格数据*/
  const [selectedRows, setSelectedRows] = useState<Record<string, any>[]>([]); /**表格选中行内容*/

  const { getSourceListRun, getSourceListLoading, getSourceListPagination, requestManage } = getSourceListService(curRes);

  // 获取所有项目列表
  const fetchGetProjectList = async (params: any) => {
    const { rows, msgFlag, msg } = await getSourceListRun(params);
    if (msgFlag) {
      message.success(msg);
      rows?.forEach((item) => {
        item.mockID = getKeyRouter();
      });
      setDataSource(rows);
      return rows;
    } else {
      message.warning(msg);
    }
  };

  // 表格复选框配置
  const rowSelection: any = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[], selectedRows: Record<string, any>[]) => {
      setSelectedRowKeys(selectedRowKeys);
      setSelectedRows(selectedRows);
    },
    type: 'radio',
  };

  // 保存信息
  const submit = async () => {
    if (!selectedRows.length) {
      message.warning('请选择标包！');
      return;
    }
    onSave(selectedRows[0]);
    onCloseModalCommon(reloadLayoutRef);
  };

  // 初始化调用接口
  useEffect(() => {
    fetchGetProjectList({ expertFlag: 0 });
  }, []);

  // 表格操作按钮
  const modalFooterRender = () => {
    return (
      <>
        <Button onClick={() => onCloseModalCommon(reloadLayoutRef)}>取消</Button>
        <Button type={'primary'} onClick={submit}>
          确认
        </Button>
      </>
    );
  };

  /** 表格分页方法改变事件 */
  const handlePaginationChange = (current, pageSize, params) => {
    fetchGetProjectList({ pageSize, current, ...params, ...searchForm.getFieldsValue(), expertID: 0 });
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={reloadLayoutRef}
        title={'标包列表'}
        width={1100}
        onCancel={onClose}
        footer={modalFooterRender()}
        bodyStyle={{
          padding: '5px 10px',
          height: '500px',
          display: 'flex',
          flexDirection: 'column',
        }}
        centered
      >
        <div className={'ProjectModalSearch'}>
          <Form form={searchForm}>
            <Row gutter={[8, 0]}>
              <Col span={4}>
                <Form.Item name={'applyTitle'}>
                  <Input placeholder="采购项目名称" />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item name={'packName'}>
                  <Input placeholder="标包名称" />
                </Form.Item>
              </Col>
              <Col span={16} style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Form.Item>
                  <Button
                    type={'default'}
                    icon={<ReloadOutlined />}
                    onClick={() => {
                      searchForm.resetFields();
                      fetchGetProjectList({ expertID: 0 });
                    }}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                    style={{ marginRight: 0, float: 'right' }}
                  >
                    重置
                  </Button>
                  <Button
                    type={'primary'}
                    icon={<SearchOutlined />}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                    style={{ marginRight: '8px', float: 'right' }}
                    onClick={() => {
                      fetchGetProjectList({ ...searchForm?.getFieldsValue(), expertID: 0 });
                    }}
                  >
                    查询
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={`list-table ProjectModalTable`}>
          <Table
            size="small"
            bordered
            scroll={{ x: 1000, y: 1000 }}
            style={{ margin: '0' }}
            rowClassName={setTableRowClassName}
            loading={getSourceListLoading}
            dataSource={dataSource}
            rowSelection={rowSelection}
            columns={getProjectTableColumns()}
            rowKey={'mockID'}
            pagination={{
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: commonPageSizeOptions,
              showTotal: showTotalInfo,
              ...getSourceListPagination,
              onChange: handlePaginationChange as any,
            }}
            onRow={(record) => {
              return {
                onClick: (event) => {
                  setSelectedRowKeys([record?.mockID]);
                  setSelectedRows([record]);
                },
              };
            }}
          />
        </div>

        {/* </div> */}
      </OneModal>
    </>
  );
};

export default SourceListModal;
